﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Workflow.Common.Dao;
using Workflow.Dto;
using NHibernate;
using NHibernate.Linq;
using Spring.Data.NHibernate.Support;

using Workflow.IDAO;
using Workflow.Model;
using Spring.Data.NHibernate;
using NHibernate.Engine;

namespace Workflow.DAO
{
	public class UserDao : RepositoryBase<User>, IUserDao
    {
		/// <summary>
		/// 根据查询条件取得分页User列表
		/// </summary>
		/// <param name="count"></param>
		/// <param name="pageIndex"></param>
		/// <param name="pageSize"></param>
		/// <param name="userQueryDto"></param>
		/// <returns></returns>
		public IList<User> GetUsersByPage(out long count, int pageIndex, int pageSize, UserQueryDto userQueryDto)
		{
			var result = Session.Query<User>();

			if (userQueryDto != null)
			{
				if (userQueryDto.UserID != null)
				{
					result = result.Where(x => x.UserID == userQueryDto.UserID);
				}
				if (!string.IsNullOrEmpty(userQueryDto.UserName))
				{
					result = result.Where(x => x.UserName == userQueryDto.UserName);
				}
				if(!(userQueryDto.UserGroupCode == "0" || string.IsNullOrEmpty(userQueryDto.UserGroupCode)))
				{
					result = result.Where(x => x.GroupId.GroupCode == int.Parse(userQueryDto.UserGroupCode));
				}
			}
			count = result.LongCount();

			result = result.OrderByDescending(x => x.UserID);

			return result.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList<User>();
		}

        /// <summary>
        /// 用户登录验证
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public UserQueryDto UserLogin(long username, string password)
        {
            var result = Session.Query<User>().Where(x=>x.UserID==username && x.Password==password &&x.IsValid==true).SingleOrDefault();
            if (result == null) return null;
            return new UserQueryDto()
                       {
                           UserGroup = result.GroupId!=null?result.GroupId.GroupName.ToString():null,
                           UserID = result.UserID,
                           UserName = result.UserName,
                           UserRole = result.RoleId!=null?result.RoleId.RoleName.ToString():null,
                           UserGroupCode = result.GroupId != null ? result.GroupId.GroupCode.ToString() : null,
                           USerRoleCode = result.RoleId != null ? result.RoleId.RoleCode.ToString() : null,
                           PassWord=result.Password
                           
                       };
        }
		/// <summary>
		/// 通过权限取得对应的用户
		/// </summary>
		public IList<User> GetUserForRole(int role)
		{
			var result = Session.Query<User>();

			result = result.Where(x => x.RoleId.RoleCode == role&&x.IsValid );
				
			return result.ToList<User>();
		}
    }
}
